const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')

// 数据初始化管理
const InitManager = require('./app/core/init')
InitManager.initCore(app)

app.use(require('koa-static')(__dirname + '/static'))

//跨域处理
const cors = require('./app/middleware/cors')
app.use(cors)

// 检测token
const auth = require('./app/middleware/auth')
app.use(auth)

// error handler
onerror(app)

// 解析
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))

app.use(json())

// ctx.url
app.use(logger())

// logger
app.use(require('./app/middleware/logger'))

// routes
const InitRouter = require('./app/api/v1/index')
InitRouter(app)

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
})

module.exports = app
